<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>订单管理</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
    <style>
        .order-card {
            border: 1px solid #ddd;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 15px;
        }
        .order-header {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .order-detail-btn {
            background: #2196F3;
            color: white;
            border: none;
            padding: 5px 10px;
            border-radius: 4px;
            cursor: pointer;
        }
        .order-modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0,0,0,0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1050;
        }
        .modal-content {
            background: white;
            padding: 20px;
            border-radius: 8px;
            width: 80%;
            max-width: 800px;
        }
        .status-badge {
            padding: 5px 10px;
            border-radius: 4px;
            font-weight: bold;
        }
        .status-pending {
            background-color: #fff3cd;
            color: #856404;
        }
        .status-paid {
            background-color: #d4edda;
            color: #155724;
        }
        .status-shipped {
            background-color: #cce5ff;
            color: #004085;
        }
        .status-completed {
            background-color: #e2e3e5;
            color: #383d41;
        }
        .status-cancelled {
            background-color: #f8d7da;
            color: #721c24;
        }
    </style>
</head>
<body>
    <div th:replace="~{common/admin-navbar :: navbar}"></div>

    <div class="container mt-4">
        <h2 class="mb-4"><i class="bi bi-cart-check"></i> 订单管理</h2>

        <div class="card mb-4">
            <div class="card-body">
                <h5 class="card-title">订单筛选</h5>
                <form id="filter-form" class="row g-3">
                    <div class="col-md-4">
                        <label for="status" class="form-label">订单状态</label>
                        <select id="status" class="form-select" name="status">
                            <option value="">全部</option>
                            <option value="待支付">待支付</option>
                            <option value="已支付">已支付</option>
                            <option value="已发货">已发货</option>
                            <option value="已完成">已完成</option>
                            <option value="已取消">已取消</option>
                        </select>
                    </div>
                    <div class="col-md-4">
                        <label for="start-date" class="form-label">开始日期</label>
                        <input type="date" id="start-date" class="form-control" name="startDate">
                    </div>
                    <div class="col-md-4">
                        <label for="end-date" class="form-label">结束日期</label>
                        <input type="date" id="end-date" class="form-control" name="endDate">
                    </div>
                    <div class="col-12">
                        <button type="submit" class="btn btn-primary">筛选</button>
                        <button type="reset" class="btn btn-secondary ms-2">重置</button>
                    </div>
                </form>
            </div>
        </div>

        <div id="orders-list">
            <!-- 订单列表将通过JavaScript动态加载 -->
            <div class="text-center my-5">
                <div class="spinner-border" role="status">
                    <span class="visually-hidden">Loading...</span>
                </div>
            </div>
        </div>
    </div>

    <!-- 订单详情弹窗 -->
    <div id="order-modal" class="order-modal" style="display: none;">
        <div class="modal-content">
            <div id="modal-content-inner"></div>
            <button class="btn btn-secondary mt-3" onclick="closeModal()">关闭</button>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
    <script>
        document.addEventListener('DOMContentLoaded', function() {
            loadOrders();

            document.getElementById('filter-form').addEventListener('submit', function(e) {
                e.preventDefault();
                loadOrders();
            });
        });

        function loadOrders() {
            const formData = new FormData(document.getElementById('filter-form'));
            const params = new URLSearchParams(formData).toString();

            fetch(`/api/orders?${params}`)
                .then(response => response.json())
                .then(orders => {
                    const ordersList = document.getElementById('orders-list');
                    if (orders.length === 0) {
                        ordersList.innerHTML = '<div class="alert alert-info">没有找到符合条件的订单</div>';
                        return;
                    }

                    let html = '';
                    orders.forEach(order => {
                        html += `
                            <div class="order-card">
                                <div class="order-header">
                                    <span>订单号: ${order.orderId}</span>
                                    <span class="status-badge status-${getStatusClass(order.status)}">
                                        ${order.status}
                                    </span>
                                </div>
                                <div class="row">
                                    <div class="col-md-4">
                                        <p>用户ID: ${order.userId}</p>
                                    </div>
                                    <div class="col-md-4">
                                        <p>总价: ¥${order.totalPrice.toFixed(2)}</p>
                                    </div>
                                    <div class="col-md-4">
                                        <p>日期: ${order.date}</p>
                                    </div>
                                </div>
                                <div class="d-flex justify-content-between">
                                    <button class="order-detail-btn" onclick="showOrderDetail('${order.orderId}')">
                                        查看详情
                                    </button>
                                    ${order.status === '已支付' ? `
                                    <div class="btn-group">
                                        <button class="btn btn-sm btn-success"
                                            onclick="updateOrderStatus('${order.orderId}', '已发货')">
                                            标记为已发货
                                        </button>
                                        <button class="btn btn-sm btn-danger"
                                            onclick="updateOrderStatus('${order.orderId}', '已取消')">
                                            取消订单
                                        </button>
                                    </div>
                                    ` : ''}
                                    ${order.status === '已发货' ? `
                                    <button class="btn btn-sm btn-primary"
                                        onclick="updateOrderStatus('${order.orderId}', '已完成')">
                                        标记为已完成
                                    </button>
                                    ` : ''}
                                </div>
                            </div>
                        `;
                    });

                    ordersList.innerHTML = html;
                });
        }

        function getStatusClass(status) {
            switch(status) {
                case '待支付': return 'pending';
                case '已支付': return 'paid';
                case '已发货': return 'shipped';
                case '已完成': return 'completed';
                case '已取消': return 'cancelled';
                default: return '';
            }
        }

        function showOrderDetail(orderId) {
            fetch(`/api/orders/detail/${orderId}`)
                .then(response => response.json())
                .then(order => {
                    const modalContent = document.getElementById('modal-content-inner');
                    modalContent.innerHTML = `
                        <h2>订单详情 #${order.orderId}</h2>
                        <div class="row mb-3">
                            <div class="col-md-6">
                                <p><strong>状态:</strong> <span class="status-badge status-${getStatusClass(order.status)}">
                                    ${order.status}
                                </span></p>
                                <p><strong>用户ID:</strong> ${order.userId}</p>
                                <p><strong>总价:</strong> ¥${order.totalPrice.toFixed(2)}</p>
                            </div>
                            <div class="col-md-6">
                                <p><strong>创建时间:</strong> ${order.date}</p>
                                <p><strong>支付方式:</strong> ${order.paymentType || '未支付'}</p>
                                <p><strong>支付账号:</strong> ${order.paymentAccount || '无'}</p>
                            </div>
                        </div>
                        <div class="mb-3">
                            <h4>物流信息</h4>
                            <p><strong>物流公司:</strong> ${order.shippingCompany || '未发货'}</p>
                            <p><strong>物流单号:</strong> ${order.shippingNo || '无'}</p>
                        </div>
                        <div class="mb-3">
                            <h4>商品列表</h4>
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th>商品名称</th>
                                        <th>单价</th>
                                        <th>数量</th>
                                        <th>小计</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    ${order.productBunches ? order.productBunches.map(item => `
                                        <tr>
                                            <td>${item.product.productName || '未知商品'}</td>
                                            <td>¥${(item.product.price || 0).toFixed(2)}</td>
                                            <td>${item.quantity || 1}</td>
                                            <td>¥${((item.product.price || 0) * (item.quantity || 1)).toFixed(2)}</td>
                                        </tr>
                                    `).join('') : '<tr><td colspan="4">暂无商品信息</td></tr>'}
                                </tbody>
                            </table>
                        </div>
                        ${order.status === '已支付' ? `
                        <div class="mb-3">
                            <h4>发货信息</h4>
                            <div class="row g-3">
                                <div class="col-md-6">
                                    <label class="form-label">物流公司</label>
                                    <input type="text" id="shipping-company" class="form-control" placeholder="输入物流公司">
                                </div>
                                <div class="col-md-6">
                                    <label class="form-label">物流单号</label>
                                    <input type="text" id="shipping-no" class="form-control" placeholder="输入物流单号">
                                </div>
                                <div class="col-12">
                                    <button class="btn btn-primary" onclick="shipOrder('${order.orderId}')">
                                        确认发货
                                    </button>
                                </div>
                            </div>
                        </div>
                        ` : ''}
                    `;

                    document.getElementById('order-modal').style.display = 'flex';
                });
        }

        function closeModal() {
            document.getElementById('order-modal').style.display = 'none';
        }

        function updateOrderStatus(orderId, status) {
            if (!confirm(`确定要将订单 ${orderId} 的状态更新为 ${status} 吗？`)) {
                return;
            }

            const data = { status: status };
            fetch(`/api/orders/update-status/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('订单状态更新成功');
                    loadOrders();
                    closeModal();
                } else {
                    alert('订单状态更新失败: ' + result.message);
                }
            });
        }

        function shipOrder(orderId) {
            const shippingCompany = document.getElementById('shipping-company').value;
            const shippingNo = document.getElementById('shipping-no').value;

            if (!shippingCompany || !shippingNo) {
                alert('请填写完整的物流信息');
                return;
            }

            const data = {
                status: '已发货',
                shippingCompany: shippingCompany,
                shippingNo: shippingNo
            };

            fetch(`/api/orders/update-status/${orderId}`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    alert('订单发货成功');
                    loadOrders();
                    closeModal();
                } else {
                    alert('订单发货失败: ' + result.message);
                }
            });
        }
    </script>
</body>
</html>
